package com.qzsoft.zhjd.common.utils;


import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.jfree.chart.*;
import org.jfree.chart.axis.*;
import org.jfree.chart.block.BlockContainer;
import org.jfree.chart.block.BorderArrangement;
import org.jfree.chart.block.EmptyBlock;
import org.jfree.chart.labels.StandardCategoryItemLabelGenerator;
import org.jfree.chart.labels.StandardPieSectionLabelGenerator;
import org.jfree.chart.plot.*;
import org.jfree.chart.renderer.category.BarRenderer;
import org.jfree.chart.renderer.category.LineAndShapeRenderer;
import org.jfree.chart.title.LegendTitle;
import org.jfree.chart.ui.RectangleEdge;
import org.jfree.chart.ui.RectangleInsets;
import org.jfree.data.category.DefaultCategoryDataset;

import java.awt.*;
import java.io.File;
import java.io.IOException;
import java.util.*;
import java.util.List;

@Slf4j
@SuppressWarnings("rawtypes")
public class ExportChartUtil {

    public static File createChartLine(List<Object[]> list, String title, String xTitle, String yTitle, String num) {

        //构造数据集合
        DefaultCategoryDataset dataset = new DefaultCategoryDataset();
        for (int i = 0; list != null && i < list.size(); i++) {
            Object[] obj = list.get(i);
            dataset.addValue(Integer.parseInt(obj[0].toString()), "数据", obj[1].toString() + "\n" + obj[2].toString());
        }

        //核心对象
        JFreeChart chart = ChartFactory.createLineChart(title,    //图形的主标题
                xTitle,                //X轴外标签的名称
                yTitle,                        //Y轴外标签的名称
                dataset,
                PlotOrientation.VERTICAL,    //图形的显示方式（水平和垂直）
                true,                        //是否显示子标题
                true,                        //是否在图形上显示数值的提示
                true);                        //是否生成URL地址
        //解决主标题的乱码
        chart.getTitle().setFont(new Font("宋体", Font.BOLD, 18));
        //解决子标题的乱码
        chart.getLegend().setItemFont(new Font("宋体", Font.BOLD, 15));
        chart.getLegend().setPosition(RectangleEdge.RIGHT);//右侧显示子菜单
        //获取图表区域对象
        CategoryPlot categoryPlot = (CategoryPlot) chart.getPlot();
//		categoryPlot.setBackgroundPaint(null);
        //获取X轴对象
        CategoryAxis categoryAxis = (CategoryAxis) categoryPlot.getDomainAxis();
        //获取Y轴对象
        NumberAxis numberAxis = (NumberAxis) categoryPlot.getRangeAxis();
        //解决X轴上的乱码
        categoryAxis.setTickLabelFont(new Font("宋体", Font.BOLD, 15));
        //解决X轴外的乱码
        categoryAxis.setLabelFont(new Font("宋体", Font.BOLD, 15));
        //解决Y轴上的乱码
        numberAxis.setTickLabelFont(new Font("宋体", Font.BOLD, 15));
        //解决Y轴外的乱码
        numberAxis.setLabelFont(new Font("宋体", Font.BOLD, 15));

        //改变Y轴的刻度，默认值从1计算
        numberAxis.setAutoTickUnitSelection(false);
        NumberTickUnit unit = new NumberTickUnit(Integer.parseInt(num));
        numberAxis.setTickUnit(unit);

        //获取绘图区域对象
        LineAndShapeRenderer lineAndShapeRenderer = (LineAndShapeRenderer) categoryPlot.getRenderer();
        lineAndShapeRenderer.setDefaultShapesVisible(true);//设置转折点

        //让数值显示到页面上
        lineAndShapeRenderer.setDefaultItemLabelGenerator(new StandardCategoryItemLabelGenerator());
        lineAndShapeRenderer.setDefaultItemLabelsVisible(true);
        lineAndShapeRenderer.setDefaultItemLabelFont(new Font("宋体", Font.BOLD, 15));

        //显示图形
//		ChartFrame chartFrame = new ChartFrame("xyz", chart);
//		chartFrame.setVisible(true);
//		chartFrame.pack();

        String filename = DateFormatUtils.format(new Date(), "yyyyMMddHHmmss") + ".png";//用时间作为文件名防止重名的问题发生
        File file = new File(filename);//保存文件到web容器中
        try {
            ChartUtils.saveChartAsPNG(file, chart, 600, 500);
        } catch (IOException e) {
            e.printStackTrace();
            log.error(e.getMessage());
        }

        return file;
    }

    public static File createChartBar(List<Object[]> list,String title,String xTitle,String yTitle,String num) {

        DefaultCategoryDataset dataset = new DefaultCategoryDataset();
        for (int i = 0; list != null && i < list.size(); i++) {
            Object[] obj = list.get(i);
            dataset.addValue(Integer.parseInt(obj[0].toString()), "数据", obj[1].toString() + "\n" + obj[2].toString());
        }

        JFreeChart chart = ChartFactory.createBarChart(title, //图表的主标题
                xTitle,//X轴（种类轴）外的标题
                yTitle,//Y轴（值轴）外的标题
                dataset,  //数据的集合
                PlotOrientation.VERTICAL, //图形的显示形式（水平/垂直）
                true, //是否生成子标题
                true, //是否生成提示的工具
                true);  //是否在图像上生成URL路径

        //处理乱码
        //处理主标题乱码
        chart.getTitle().setFont(new Font("宋体", Font.BOLD, 18));
        //处理子标题乱码
        chart.getLegend().setItemFont(new Font("宋体", Font.BOLD, 15));
        chart.getLegend().setPosition(RectangleEdge.RIGHT);//右侧显示子菜单
        //调出图表区域对象
        CategoryPlot categoryPlot = (CategoryPlot) chart.getPlot();
        //获取到X轴
        CategoryAxis categoryAxis = (CategoryAxis) categoryPlot.getDomainAxis();
        //获取到Y轴
        NumberAxis numberAxis = (NumberAxis) categoryPlot.getRangeAxis();
        //处理X轴外的乱码
        categoryAxis.setLabelFont(new Font("宋体", Font.BOLD, 15));
        //处理X轴上的乱码
        categoryAxis.setTickLabelFont(new Font("宋体", Font.BOLD, 15));
        //处理Y轴外的乱码
        numberAxis.setLabelFont(new Font("宋体", Font.BOLD, 15));
        //处理Y轴上的乱码
        numberAxis.setTickLabelFont(new Font("宋体", Font.BOLD, 15));

        //处理Y轴上的刻度，默认从1开始
        numberAxis.setAutoTickUnitSelection(false);
        NumberTickUnit unit = new NumberTickUnit(Integer.parseInt(num));
        numberAxis.setTickUnit(unit);

        //处理图形，先要获取绘图区域对象
        BarRenderer barRenderer = (BarRenderer) categoryPlot.getRenderer();
        //设置图形的宽度
//		barRenderer.setMaximumBarWidth(0.1);

        //在图形上显示对应数值
        barRenderer.setDefaultItemLabelGenerator(new StandardCategoryItemLabelGenerator());
        barRenderer.setDefaultItemLabelsVisible(true);
        barRenderer.setDefaultItemLabelFont(new Font("宋体", Font.BOLD, 15));

        String filename = DateFormatUtils.format(new Date(), "yyyyMMddHHmmss") + ".png";
        File file = new File(filename);
        try {
            ChartUtils.saveChartAsPNG(file, chart, 600, 500);
        } catch (IOException e) {
            e.printStackTrace();
            log.error(e.getMessage());
        }

        return file;
    }


    public static File createPieChart(String title, CountTopData countTopData) {
        List<Map<String,Object>> list = countTopData.getBarChar();
        DefaultCategoryDataset dataset = new DefaultCategoryDataset();
        list.stream().forEach(m -> {
            countTopData.getColumns().stream().forEach(s ->{
                    for(String k:m.keySet()){
                        for(String sk:s.keySet()){
                            if(k.equals(sk)){
                                dataset.addValue(Double.valueOf(String.valueOf(m.get(k))), s.get(sk),String.valueOf(m.get(countTopData.getCategoryName())));
                            }
                    }
                }

            });
        });
        //创建主题样式
        StandardChartTheme mChartTheme = new StandardChartTheme("CN");
        mChartTheme.setExtraLargeFont(new Font("宋体", Font.BOLD, 18));
        ChartFactory.setChartTheme(mChartTheme);
        JFreeChart chart = ChartFactory.createBarChart(countTopData.getTitle(), "", "", dataset);
        //处理主标题乱码
        chart.getTitle().setFont(new Font("宋体", Font.BOLD, 18));
        CategoryPlot plot = (CategoryPlot)chart.getPlot();

        plot.mapDatasetToRangeAxis(1, 1);

        CategoryAxis domainAxis = plot.getDomainAxis();
        chart.getLegend().setItemFont(new Font("宋体", Font.PLAIN, 12));
        domainAxis.setCategoryLabelPositions(CategoryLabelPositions.DOWN_45);
        domainAxis.setTickLabelFont(new Font("宋体", Font.PLAIN, 12));
//        LegendTitle legend1 = new LegendTitle(plot.getRenderer(0));
        LegendTitle legend2 = new LegendTitle(plot.getRenderer(1));
        BlockContainer container = new BlockContainer(new BorderArrangement());
        container.add(legend2, RectangleEdge.BOTTOM);
        container.add(new EmptyBlock(2000.0D, 0.0D));
        String filename = DateFormatUtils.format(new Date(), "yyyyMMddHHmmss") + ".png";
        File file = new File(filename);
        try {
            ChartUtils.saveChartAsPNG(file, chart, 1200, 500);
        } catch (IOException e) {
            e.printStackTrace();
            log.error(e.getMessage());
        }
        return file;
    }
    private static String NO_DATA_MSG = "数据加载失败";
    public static void setPieRender(Plot plot) {
        plot.setNoDataMessage(NO_DATA_MSG);
        plot.setInsets(new RectangleInsets(10, 10, 5, 10));
        PiePlot piePlot = (PiePlot) plot;
        piePlot.setInsets(new RectangleInsets(0, 0, 0, 0));
        piePlot.setCircular(true);// 圆形
        // piePlot.setSimpleLabels(true);// 简单标签
        piePlot.setLabelGap(0.01);
        piePlot.setInteriorGap(0.05D);
        piePlot.setLegendItemShape(new Rectangle(10, 10));// 图例形状
        piePlot.setIgnoreNullValues(true);
        piePlot.setLabelBackgroundPaint(null);// 去掉背景色
        piePlot.setLabelShadowPaint(null);// 去掉阴影
        piePlot.setLabelOutlinePaint(null);// 去掉边框
        piePlot.setShadowPaint(null);
        // 0:category 1:value:2 :percentage
        piePlot.setLabelGenerator(new StandardPieSectionLabelGenerator(
                "{0}:{2}"));// 显示标签数据
    }

}
